package com.ruoyi.whole.controller;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.baselibrary.infotargetsystem.service.IInfoTargetSystemService;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.whole.domain.*;
import com.ruoyi.whole.service.IInfoWholeIndexService;
import com.ruoyi.whole.service.IInfoWholePlanService;
import com.ruoyi.whole.service.IInfoWholeTargetService;
import freemarker.template.Configuration;
import com.ruoyi.common.config.RuoYiConfig;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.whole.service.IInfoWholeEvaluateService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;


/**
 * 部门自评Controller
 *
 * @author ruoyi
 * @date 2022-02-14
 */
@RestController
@RequestMapping("/whole/evaluate")
@Api(tags = "部门自评")
public class InfoWholeEvaluateController extends BaseController
{
    @Autowired
    private IInfoWholeEvaluateService infoWholeEvaluateService;
    @Autowired
    private IInfoWholeTargetService infoWholeTargetService;
    @Autowired
    private IInfoWholeIndexService iInfoWholeIndexService;
    @Autowired
    private IInfoTargetSystemService infoTargetSystemService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IInfoWholePlanService iInfoWholePlanService;
    @Autowired
    private ISysRoleService sysRoleService;
    /**
     * 查询部门自评列表
     */
    @PreAuthorize("@ss.hasPermi('whole:evaluate:list')")
    @GetMapping("/list")
    public TableDataInfo list(InfoWholeEvaluate infoWholeEvaluate)
    {
        startPage();
        List<InfoWholeEvaluate> list = infoWholeEvaluateService.selectInfoWholeEvaluateList(infoWholeEvaluate);
        return getDataTable(list);
    }

    /**
     * 导出部门自评列表
     */
    @PreAuthorize("@ss.hasPermi('whole:evaluate:export')")
    @Log(title = "部门自评", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InfoWholeEvaluate infoWholeEvaluate)
    {
        List<InfoWholeEvaluate> list = infoWholeEvaluateService.selectInfoWholeEvaluateList(infoWholeEvaluate);
        ExcelUtil<InfoWholeEvaluate> util = new ExcelUtil<InfoWholeEvaluate>(InfoWholeEvaluate.class);
        util.exportExcel(response, list, "部门自评数据");
    }

    /**
     * 获取部门自评详细信息
     */
    @PreAuthorize("@ss.hasPermi('whole:evaluate:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(infoWholeEvaluateService.selectInfoWholeEvaluateById(id));
    }

    /**
     * 新增部门自评
     */
    @PreAuthorize("@ss.hasPermi('whole:evaluate:add')")
    @Log(title = "部门自评", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InfoWholeEvaluate infoWholeEvaluate)
    {
        return toAjax(infoWholeEvaluateService.insertInfoWholeEvaluate(infoWholeEvaluate));
    }

    /**
     * 修改部门自评
     */
    @PreAuthorize("@ss.hasPermi('whole:evaluate:edit')")
    @Log(title = "部门自评", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InfoWholeEvaluate infoWholeEvaluate)
    {
        return toAjax(infoWholeEvaluateService.updateInfoWholeEvaluate(infoWholeEvaluate));
    }

    /**
     * 删除部门自评
     */
    @PreAuthorize("@ss.hasPermi('whole:evaluate:remove')")
    @Log(title = "部门自评", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(infoWholeEvaluateService.deleteInfoWholeEvaluateByIds(ids));
    }

    /**
     * 部门整体评价报告下载
     */
    @PostMapping("/download/{id}")
    @ResponseBody
    @ApiOperation("部门整体评价报告下载")
    @ApiImplicitParam(name = "id", value = "编号", dataType = "Long")
    public AjaxResult download(@PathVariable("id")Long id) {
        String fileName = null;

        /**
         * DeptEvaluate部门自评表 info_dept_evaluate根据id查自评表里的数据
         */
        InfoWholeEvaluate infoWholeEvaluate = infoWholeEvaluateService.selectInfoWholeEvaluateById(id);
        /**
         * deptId部门编号获取自评表里的部门编号
         */
        Long wholeId = infoWholeEvaluate.getWholeId();

        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            String dirPath = InfoWholeTargetController.class.getResource("/report/template").getPath();
            configuration.setDirectoryForTemplateLoading(new File(dirPath));
            Template template = configuration.getTemplate("bm.ftl", "utf-8");
            /**
             * 把查到的东西放进map中
             */
            Map<String, Object> data = new HashMap<>();


            /**
             * 部门整体信息表 info_dept_target根据department_id查信息
             */
            InfoWholeTarget infoWholeTarget = infoWholeTargetService.selectInfoWholeTargetsById(wholeId);

            List<InfoWholePlan> infoWholePlanss=iInfoWholePlanService.selectInfoWholePlansId(infoWholeTarget.getId());
            BigDecimal subTotalRental=new BigDecimal("0");

            for(InfoWholePlan infoWholePlan:infoWholePlanss){
                if(ObjectUtil.isNotEmpty(infoWholePlan.getBudgetRental())){
                    subTotalRental=subTotalRental.add(infoWholePlan.getBudgetRental());
                }
            }
            //获取全年支出（年初预算数）
            data.put("subTotalRental", subTotalRental);
            /**
             * 查询部门信息
             */
            SysDept dept = deptService.selectDeptsById(infoWholeTarget.getDepartmentId());
            String title =dept.getParentName() + dept.getDeptName() + "2022年部门整体支出";
            fileName = title;

            /**
             * map里放的东西
             */
            data.put("fileName", title);
            //现在map里的东西是title，部门整体信息target和自评表的东西
            data.put("infoWholeTarget", infoWholeTarget);
            data.put("infoWholeEvaluate", infoWholeEvaluate);

            /**
             * 根据部门自评表里的部门编号查询部门指标信息里的对应信息
             */
            List<InfoWholeIndex> infoWholeIndices = iInfoWholeIndexService.selectInfoWholeIndicesId(infoWholeTarget.getId());
            //等会看总分
            int deptZbZongfen = 0;
            int deptZbDfs = 0;


            for (int i = 0; i < infoWholeIndices.size(); i++) {
                InfoWholeIndex infoWholeIndex = infoWholeIndices.get(i);

                //一级指标
                String targetOnes = "";
                //指标体系
                String targetTwos = "";

                /**
                 *  判断指标体系是否不为空
                 */
                if (StringUtils.isNotBlank(infoWholeIndex.getIndexId())) {

                    // target_value是数值
                    Long systemId = Long.parseLong(infoWholeIndex.getIndexId());

                    /**
                     * TargetSystem指标体系info_target_system 根据indexId查询指标体系里的信息
                     */
//                    InfoTargetSystem targetSystem = infoTargetSystemService.selectInfoTargetSystemById(systemId);
//
//                    //指标体系里的名称
//                    targetTwos = targetSystem.getName();
//                    //指标体系里的父名称
//                    targetOnes = targetSystem.getParentName();
//
//
//                    InfoWholeIndex infoWholeIndex1 = infoWholeIndices.get(i);
//
//                    infoWholeIndex1.setTargetOne(targetOnes);
//                    infoWholeIndex1.setTargetTwo(targetTwos);

                    /**
                     * score分值goal得分
                     */
                    if(!org.springframework.util.StringUtils.isEmpty(infoWholeIndex.getTargetScore())){
                        deptZbZongfen += Integer.parseInt(infoWholeIndex.getTargetScore());
                    }
                    if(!org.springframework.util.StringUtils.isEmpty(infoWholeIndex.getTargetGoal())){
                        deptZbDfs += Integer.parseInt(infoWholeIndex.getTargetGoal());
                    }
                }
            }
            //指标的分数
            infoWholeTarget.setZbzongfen(deptZbZongfen + "");
            infoWholeTarget.setZbdfs(deptZbDfs + "");
            data.put("infoWholeIndices", infoWholeIndices);
            data.put("year", DateUtils.parseDateToStr("yyyy",new Date()));



            /* ----------------------  项目部分开始  ----------------------  */

            /**
             * ProjectInfos建了一个包含部门整体和部门自评表，部门指标的一个实体类
             */
            List<ProjectInfos> projectInfosList = new LinkedList<>();

            /**
             * 项目整体信息表info_whole_target
             */
            List<InfoWholeTarget> infoWholeTargets = infoWholeTargetService.selectProjectByDeptId(dept.getDeptId());


            for (int i = 0; i < infoWholePlanss.size(); i++) {
                ProjectInfos projectInfos = new ProjectInfos();
                //任务信息
                InfoWholePlan infoWholePlan=infoWholePlanss.get(i);
                projectInfos.setInfoWholePlans(infoWholePlan);

                /**
                 * 根据项目支出指标信息查询
                 */
                    /*项目支出整体信息*/
                    InfoWholeTarget infoWholeTarget2 = infoWholeTargetService.selectInfoWholeTargetById(infoWholePlan.getWholeId());
                    /*项目支出指标信息*/
                    InfoWholeIndex infoWholeIndex = new InfoWholeIndex();
//                projectTarget.setProjectId(1722L);
                    //指标对象的项目编号
                    infoWholeIndex.setWholeId(infoWholeTarget2.getId());
                    List<InfoWholeIndex> infoWholeIndices1 = iInfoWholeIndexService.selectInfoWholeIndexList(infoWholeIndex);
                    projectInfos.setInfoWholeTarget(infoWholeTarget2);

                    /*项目支出自评信息*/
                    List<InfoWholeEvaluate>  infoWholeEvaluate1 = infoWholeEvaluateService.selectProjectEvaluateByProjectId(infoWholeTarget2.getId());
                    projectInfos.setInfoWholeEvaluates(infoWholeEvaluate1);



                    // 各个指标项目计算总分
                    Double zBzongfeng = 0D;
                    // 各个指标项目计算得分
                    Double zBdfs = 0D;


                    for (int j = 0; j < infoWholeIndices1.size(); j++) {
                        InfoWholeIndex infoWholeIndex1 = infoWholeIndices1.get(j);
//                        String targetOnes = "";
//                        String targetTwos = "";
//                        if (StringUtils.isNotBlank(infoWholeIndex1.getIndexId())) {
//                            Long systemsId = Long.parseLong(infoWholeIndex1.getIndexId());
//                            targetTwos = infoTargetSystemService.selectInfoTargetSystemById(systemsId).getName();
//                            targetOnes = infoTargetSystemService.selectInfoTargetSystemById(systemsId).getParentName();
//                            infoWholeIndices1.get(j).setTargetOne(targetOnes);
//                            infoWholeIndices1.get(j).setTargetTwo(targetTwos);
//                        }
                        if(!org.springframework.util.StringUtils.isEmpty(infoWholeIndex1.getTargetScore())){
                            zBzongfeng += Double.parseDouble(infoWholeIndex1.getTargetScore());
                        }
                        if(!org.springframework.util.StringUtils.isEmpty(infoWholeIndex1.getTargetGoal())){
                            zBdfs += Double.parseDouble(infoWholeIndex1.getTargetGoal());
                        }
                    }
                    infoWholeTarget2.setZbzongfen(zBzongfeng + "");
                    infoWholeTarget2.setZbdfs(zBdfs + "");
                    projectInfos.setInfoWholeIndices(infoWholeIndices1);
                    projectInfosList.add(projectInfos);



            }
            data.put("projectInfosList", projectInfosList);
            /*  ----------------------  项目部分结束  ----------------------  */


            /* ----------------------  项目汇总表开始  ----------------------  */
            List<InfoWholeSummarizingVo> infoWholeSummarizingVos = new ArrayList<>();
            for(int j=0;j<infoWholePlanss.size();j++){
                InfoWholeSummarizingVo s = new InfoWholeSummarizingVo();
                s.setXh(j + 1);
                InfoWholePlan project2 = infoWholePlanss.get(j);
                s.setTaskName(project2.getTaskName());
                s.setAnnualNumberOfExecutions(project2.getAnnualNumberOfExecutions());
                s.setBudgetFiscalAppropriation(project2.getBudgetFiscalAppropriation());
                s.setBudgetOthers(project2.getBudgetOthers());
                s.setImplementationRate(project2.getImplementationRate());
                s.setCarryForwardTheMoney(project2.getCarryForwardTheMoney());
                BigDecimal subTotal=new BigDecimal("0");
                if(ObjectUtil.isNotEmpty(s.getBudgetOthers())){
                    subTotal=subTotal.add(s.getBudgetOthers());
                }
                if(ObjectUtil.isNotEmpty(s.getCarryForwardTheMoney())){
                    subTotal=subTotal.add(s.getCarryForwardTheMoney());
                }
                if(ObjectUtil.isNotEmpty(s.getBudgetFiscalAppropriation())){
                    subTotal=subTotal.add(s.getBudgetFiscalAppropriation());
                }
                s.setSubTotal(subTotal+"");
                /*for (int i = 0; i < infoWholeTargets.size(); i++) {
                InfoWholeTarget project1 = infoWholeTargets.get(i);
                s.setIndustryTitle(project1.getIndustryTitle());
                }*/
                s.setIndustryTitle(infoWholeTargets.get(0).getDepartmentName());
                infoWholeSummarizingVos.add(s);
            }
            data.put("infoWholeSummarizingVos", infoWholeSummarizingVos);
            System.out.println(JSON.toJSONString(data));
            /* ----------------------  项目汇总表结束  ---------------------- */
            Writer out = null;

            String downloadPath = RuoYiConfig.getDownloadPath() + fileName;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
            File outFile = new File(downloadPath + ".doc");
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(data, out);
            out.close();
            System.out.println("................word文档生成成功 !.............");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }


        return AjaxResult.success(fileName + ".doc");
    }



    /**
     * 查询评价列表
     * @param infoWholeEvaluate
     * @return
     */
    @GetMapping("/pjlist")
    public TableDataInfo pjlist(InfoWholeEvaluate infoWholeEvaluate) {
        startPage();
        Long userId= SecurityUtils.getUserId();
        List<SysRole> roles=sysRoleService.selectRolesByUserIdList(userId);
        Optional.ofNullable(roles).orElseThrow(() -> new RuntimeException("该登录用户没有角色信息！"));
        List<String> rileKeys=roles.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        if(rileKeys.contains("sjc")){
            //查询创建该项目部门所有信息
            infoWholeEvaluate.setDepartmentId(SecurityUtils.getDeptId());
            List<InfoWholeEvaluate> list = infoWholeEvaluateService.selectInfoWholeEvaluateList(infoWholeEvaluate);
            return getDataTable(list);
        }else{
            //只查询当前登录人的处室Id
            infoWholeEvaluate.setDeptId(SecurityUtils.getDeptId());
            List<InfoWholeEvaluate> list = infoWholeEvaluateService.selectInfoWholeEvaluateList(infoWholeEvaluate);
            return getDataTable(list);
        }
    }

    /**
     * 预算单位 查询部门评价列表
     */
    @GetMapping("/budgetUnitList")
    public TableDataInfo budgetUnitList(InfoWholeEvaluate infoWholeEvaluate) {
        //只查询release_department_id等于当前登录人的处室Id

        infoWholeEvaluate.setReleaseDepartmentId(SecurityUtils.getDeptId());
        startPage();
        List<InfoWholeEvaluate> list = infoWholeEvaluateService.selectInfoWholeEvaluateList(infoWholeEvaluate);
        return getDataTable(list);
    }
    /**
     * 获取部门自评的详细信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getBmEvaluateDetail/{id}", method = RequestMethod.GET)
    public AjaxResult getBmEvaluateDetail(@PathVariable("id") Long id) {
        InfoBulkAddVo infoBulkAddVo = infoWholeEvaluateService.getBmEvaluateDetail(id);
        return AjaxResult.success(infoBulkAddVo);
    }
    /**
     * 修改评价审核状态
     * 下达 examineStatus 审核状态 0 待下达 1 待填报 2 待审核 3 通过 4 已退回
     *
     * @return
     */
    @RequestMapping(value = "/editExamineEvaluate", method = RequestMethod.POST)
    public AjaxResult editExamineEvaluate(@RequestBody InfoWholeEvaluate infoWholeEvaluate) {
        InfoBulkAddVo infoBulkAddVo = new InfoBulkAddVo();
        infoBulkAddVo.setInfoWholeEvaluate(infoWholeEvaluate);
        return AjaxResult.success(infoWholeEvaluateService.editExamineEvaluate(infoBulkAddVo));
    }

    /**
     * 上传文件
     */
    @RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
    public AjaxResult uploadFiles(@RequestBody  InfoWholeEvaluate infoWholeEvaluate) {
        return toAjax(infoWholeEvaluateService.uploadFiles(infoWholeEvaluate));
    }

}
